package com.vcc.boss.core.component;

import com.alibaba.fastjson2.JSONObject;
import com.vcc.boss.core.config.AliIpConfig;
import com.vcc.core.exception.ProgramException;
import com.vcc.core.util.RegexUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class AliIpComponent {

    @Autowired
    private AliIpConfig aliIpConfig;
    @Autowired
    private RestTemplate restTemplate;

    public JSONObject ipToAddress(String ip) {
        JSONObject resultMap;
        try {
            String url = aliIpConfig.getUrl() + "?ip=" + ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip) ? "localhost" : ip);
            ResponseEntity<String> response =
                    restTemplate.exchange(
                            url,
                            HttpMethod.GET,
                            new HttpEntity<String>(getAccessTokenHeader()),
                            String.class
                    );
            resultMap = JSONObject.parseObject(response.getBody());
            if (RegexUtil.checkObjectIsNull(resultMap)) {
                throw new ProgramException("系统异常");
            }
            if ("200".equals(resultMap.getString("ret"))) {
                resultMap = resultMap.getJSONObject("data");
            }
        } catch (Exception e){
            resultMap = null;
        }
        return resultMap;
    }


    private HttpHeaders getAccessTokenHeader() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "APPCODE " + aliIpConfig.getAppCode());
        return headers;
    }
}
